package org.dk.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.dk.shiro.MyRealm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfiguration {

    //配置Shiro的过滤器工厂类
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Autowired DefaultWebSecurityManager securityManager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        /*添加shiro的过滤器
        *
        * anon：  不需要认证，不需要登录也能访问
        * authc: 必须登录才能访问
        * perms : 必须登录，但是登录之后还要看你有没有权限
        * role:  必须登录，但是登录之后还要看你有哪些角色
        * */

            Map<String,String> map  = new LinkedHashMap<>();
            map.put("/logout","logout");
            map.put("/**","anon");


        //设置过滤器链,基于过滤器的,四个过滤器
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        shiroFilterFactoryBean.setLoginUrl("/userController/toLogin");
        return shiroFilterFactoryBean;
    }

    //配置SecurityManager
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(@Autowired MyRealm myRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //关联realm类
        securityManager.setRealm(myRealm);
        return securityManager;
    }



    @Bean
    public MyRealm getMyRealm(@Autowired HashedCredentialsMatcher hashedCredentialsMatcher){
        MyRealm myRealm = new MyRealm();
        myRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return myRealm;
    }


    //开启密文加密
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        //指定加密方式
        matcher.setHashAlgorithmName("MD5");
        //加密的次数
        matcher.setHashIterations(3);
        //设置一下编码
        matcher.setStoredCredentialsHexEncoded(true);

        return matcher;
    }


    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
